import {StyleSheet, Text, TouchableOpacity, View, Image, ImageBackground, ScrollView, Dimensions} from 'react-native'
import React, {useEffect, useState, useRef} from 'react'
import PageScrollView from "@/components/PageScrollView";
import PageTabBar from "@/components/PageTabBar";
import FcButton from "@/components/FcButton";
import FcModal from '@/components/FcModal';
import {Video} from 'expo-av';
import {StatusBar} from "expo-status-bar";
import {router, useLocalSearchParams} from "expo-router";
import {Toast, Flex} from "@ant-design/react-native";
import { useFocusEffect } from '@react-navigation/native';

import {
  useGetWorksMutation,
  useQueryTaskStatusMutation,
  useDeleteBatchMutation,
  useReGenerateMutation
} from "@/store/api/videoAndPictrue/videoAndPictrueApi";

type Props = {}

const works = (props: Props) => {
  const [worksObj,setWorksObj] = useState<any>({})
  const [activeIndex,setActiveIndex] = useState<any>(0)
  const [deleteOpen,setDeleteOpen] = useState(false)
  const [pageScrollBodyH, setPageScrollBodyH] = useState(0)

  const timer:any = useRef(null)
  
  const [genWorksFun] = useGetWorksMutation()
  const [queryTaskStatusFun] = useQueryTaskStatusMutation()
  const [deleteBatchFun] = useDeleteBatchMutation()
  const [reGenerateFun] = useReGenerateMutation()

  const {id} = useLocalSearchParams()
  
  useEffect(() => {
    if(id){
      handleGetWorks(id)
    }
  }, [id]);

  const getScrollBodyInfo = ({height}) => {
    setPageScrollBodyH(height)
  }

  const handleGetWorks = (id:any) => {
    genWorksFun({pageNo: 1, pageSize: 10, id: id}).then(res => {
      if(res.data?.result?.records.length == 0) return

      let obj = res.data?.result?.records[0]
      let arr = obj.detailList.filter((val:any) => val.taskStatus == 'submitted' || val.taskStatus == 'processing')
      setWorksObj(obj)

      if(arr.length > 0){
        clearInterval(timer.current)

        timer.current = setInterval(() => {
          handleQueryTaskStatus(obj.id)
        }, 10000)
      }
    })
  }

  useFocusEffect(
    React.useCallback(() => {
      return () => {
        clearInterval(timer.current)
      };
    }, [])
  );

  //获取作品生成状态
  const handleQueryTaskStatus = (id:any) => {
    queryTaskStatusFun({ids: id}).then(res => {
      let arr = res.data.result?.[0].detailList.filter((val:any) => val.taskStatus == 'submitted' || val.taskStatus == 'processing')
      if(arr.length == 0){
        clearInterval(timer.current)
      }
      setWorksObj(res.data.result[0])
    })
  }

  //删除
  const handleDelete = () => {
    deleteBatchFun({ids: worksObj.id}).then(res => {
      router.back()
      Toast.info('删除成功')
    })
  }

  //通过URL下载视频或图片
  const handleDownload = () => {
    // let xhr = new XMLHttpRequest();
    // xhr.open("GET", item.viewUrl || item.ownViewUrl, true);
    // xhr.responseType = "blob";
    // xhr.onload = function () {
    //   if (xhr.readyState === 4 && xhr.status === 200) {
    //     let a = document.createElement("a");
    //     a.href = window.URL.createObjectURL(new Blob([xhr.response], { type: worksObj.type == 1 ? 'image/png' : 'video/mp4' }));
    //     a.download = item.id;
    //     document.body.appendChild(a);
    //     a.click();
    //     a.remove();
    //   }
    // };
    // xhr.send();
  }

  //再次生成
  const handleReGenerate = () => {
    reGenerateFun({id: worksObj.id}).then(res => {
      handleGetWorks(worksObj.id)
    })
  }

  return (
    <View style={{flex: 1, backgroundColor: '#171923'}}>
      <StatusBar style='light'></StatusBar>
      <ImageBackground 
        source={require('@/assets/images/public/black_bg.png')}
        style={{flex: 1, width: '100%'}}
      >
        <PageScrollView
          isTransparentTab
          getPageScrollBodyInfo={getScrollBodyInfo}
          themedStyle={{backgroundColor: 'transparent'}}
          pageTab={
            <PageTabBar
              style={{marginVertical: 10, padding: 0}}
              titleStyle={{color: '#FFF'}}
              title={'AI作品'}
              // right={
              //   <TouchableOpacity onPress={() => router.push(`/videoAndPictrue/worksAll?type=${worksObj.type}`)}>
              //     <Text style={{color: '#FFF'}}>所有{worksObj.type == 0 ? '视频' : '图片'}</Text>
              //   </TouchableOpacity>
              // }
              left={
                <Flex style={{paddingLeft: 16}}>
                  <TouchableOpacity onPress={() => router.back()}>
                    <Text style={{fontFamily: 'FcIconFont', fontSize: 25, color: '#FFF', marginRight: 3}}>&#xe659;</Text>
                  </TouchableOpacity>

                  <TouchableOpacity onPress={() => router.push('/videoAndPictrue')}>
                    <Text style={{fontFamily: 'FcIconFont', fontSize: 25, color: '#FFF', marginRight: 3}}>&#xe61a;</Text>
                  </TouchableOpacity>
                </Flex>
              }
            />
          }
          pageBottom={
            <Flex justify='between' style={{height: 56, backgroundColor: '#1B1D2A', paddingHorizontal: 10}}>
              <FcButton
                onClick={() => setDeleteOpen(true)}
                type='BjJB'
                colors={['#26293D', '#26293D']}
                style={{width: '30%', height: 40, justifyContent: 'center'}}
                itemStyle={{borderRadius: 8, fontSize: 15}}
                textName='删除'
              />
              <FcButton
                onClick={() => handleDownload()}
                type='BjJB'
                colors={['#26293D', '#26293D']}
                style={{width: '30%', height: 40, justifyContent: 'center'}}
                itemStyle={{borderRadius: 8, fontSize: 15}}
                textName='下载'
              />
              <FcButton
                onClick={() => handleReGenerate()}
                type='BjJB'
                colors={['#6989FF', '#C65EFD']}
                style={{width: '30%', height: 40, justifyContent: 'center'}}
                itemStyle={{borderRadius: 8, fontSize: 15}}
                textName='再次生成'
              />
            </Flex>
          }
        >
          <View>
            {
              worksObj.detailList?.length == 1 ?
              <View style={[styles.works_box, {height: pageScrollBodyH - 16}]}>
                {
                  worksObj.detailList?.[activeIndex].taskStatus == 'submitted' || worksObj.detailList?.[activeIndex].taskStatus == 'processing' ?
                  <Flex direction='column' justify='center' style={{flex: 1}}>
                    <Image style={{width: 150, height: 100}} resizeMode={'cover'} source={require('@/assets/images/loading.gif')}></Image>
                    <Text style={{color: '#6989FF'}}>视频生成中</Text>
                  </Flex>
                  :
                  // <View style={{height: worksObj.aspectRatio == '9:16' ? Dimensions.get('window').height - 150 : 212}}>
                  <Flex style={{flex: 1}}>
                    {
                      worksObj.type == 0 ?
                      <Video
                        style={{ width: '100%', height: '100%' }}
                        source={{ uri: worksObj.detailList?.[activeIndex].viewUrl }} // 视频 URL
                        useNativeControls
                        resizeMode="contain"
                        isLooping={false}
                      />
                      :
                      <Image style={{width: '100%', height: '100%', borderRadius: 8}} resizeMode={'contain'} source={{uri: worksObj.detailList?.[activeIndex].viewUrl}}></Image>
                    }
                  </Flex>
                }
              </View>
              :
              <View>
                <View style={{height: worksObj.aspectRatio == '9:16' ? 400 : 212, backgroundColor: '#21232F'}}>
                  {
                    worksObj.detailList?.[activeIndex].taskStatus == 'submitted' || worksObj.detailList?.[activeIndex].taskStatus == 'processing' ?
                    <Flex direction='column' justify='center' style={{flex: 1}}>
                      <Image style={{width: 100, height: 70}} resizeMode={'cover'} source={require('@/assets/images/loading.gif')}></Image>
                      <Text style={{fontSize: 12, color: '#6989FF'}}>视频生成中</Text>
                    </Flex>
                    :
                    worksObj.type == 0 ?
                    <Video
                      style={{ width: '100%', height: '100%' }}
                      source={{ uri: worksObj.detailList?.[activeIndex].viewUrl }} // 视频 URL
                      useNativeControls
                      resizeMode="contain"
                      isLooping={false}
                    />
                    :
                    <Image style={{width: '100%', height: '100%', borderRadius: 8}} resizeMode={'contain'} source={{uri: worksObj.detailList?.[activeIndex].viewUrl}}></Image>
                  }
                </View>
                
                {
                  worksObj.aspectRatio == '9:16' ?
                  <ScrollView
                    horizontal
                    showsHorizontalScrollIndicator={false}
                    contentContainerStyle={{paddingVertical: 10}}
                  >
                    {
                      worksObj.detailList?.map((item:any, index:any) => (
                        <TouchableOpacity key={index} onPress={() => setActiveIndex(index)}>
                          <View style={[styles.works_img_V, activeIndex == index ? {borderWidth: 1} : null, item.taskStatus == 'submitted' || item.taskStatus == 'processing' ? {backgroundColor: '#232532'} : null]}>
                            {
                              item.taskStatus == 'submitted' || item.taskStatus == 'processing' ? 
                              <Flex direction='column' justify='center' style={{flex: 1}}>
                                <Image style={{width: 100, height: 70}} resizeMode={'cover'} source={require('@/assets/images/loading.gif')}></Image>
                                <Text style={{fontSize: 12, color: '#6989FF'}}>视频生成中</Text>
                              </Flex>
                              :
                              <Image style={{width: '100%', height: '100%', borderRadius: 8}} resizeMode={'contain'} source={{uri: worksObj.type == 0 ? item.thumbnail : item.viewUrl}}></Image>
                            }
                            <View style={styles.works_img_bottom}>
                              <Text style={{color: '#FFF', textAlign: 'center', fontSize: 12}}>第<Text style={{color: '#FA5151', fontSize: 12}}>{index + 1}</Text>{worksObj.type == 0 ? '条视频' : '张图片'}</Text>
                              {
                                activeIndex == index ?
                                <View>
                                  <View style={styles.works_active}></View>
                                  <Text style={styles.works_active_icon}>&#xe64d;</Text>
                                </View>
                              : null
                              }
                            </View>
                          </View>
                        </TouchableOpacity>
                      ))
                    }
                  </ScrollView>
                  :
                  <Flex style={{paddingVertical: 10}} wrap='wrap' justify='between'>
                    {
                      worksObj.detailList?.map((item:any, index:any) => (
                        <TouchableOpacity style={{width: '48.6%'}} key={index} onPress={() => setActiveIndex(index)}>
                          <View style={[styles.works_img_H, activeIndex == index ? {borderWidth: 1} : null, item.taskStatus == 'submitted' || item.taskStatus == 'processing' ? {backgroundColor: '#232532'} : null]}>
                            {
                              item.taskStatus == 'submitted' || item.taskStatus == 'processing' ? 
                              <Flex direction='column' justify='center' style={{height: '80%'}}>
                                <Image style={{width: 70, height: 40}} resizeMode={'cover'} source={require('@/assets/images/loading.gif')}></Image>
                                <Text style={{fontSize: 12, color: '#6989FF'}}>视频生成中</Text>
                              </Flex>
                              :
                              <Image style={{width: '100%', height: '100%', borderRadius: 8}} resizeMode={'cover'} source={{uri: worksObj.type == 0 ? item.thumbnail : item.viewUrl}}></Image>
                            }
                            <View style={styles.works_img_bottom}>
                              <Text style={{color: '#FFF', textAlign: 'center', fontSize: 12}}>第<Text style={{color: '#FA5151', fontSize: 12}}>{index + 1}</Text>{worksObj.type == 0 ? '条视频' : '张图片'}</Text>
                              {
                                activeIndex == index ?
                                <View>
                                  <View style={styles.works_active}></View>
                                  <Text style={styles.works_active_icon}>&#xe64d;</Text>
                                </View>
                              : null
                              }
                            </View>
                          </View>
                        </TouchableOpacity>
                      ))
                    }
                  </Flex>
                }
              </View>
            }
          </View>

          {/* 删除弹窗 */}
          <FcModal
            isOpen={deleteOpen}
            transparent
            closeShow={false}
            animationType='fade'
            onFcModalClose={() => setDeleteOpen(false)}
            style={{width: 280, borderBottomRightRadius: 12, borderBottomLeftRadius: 12}}
            titleText={'确认要删除吗？'}
            titleBottomBorderWidth={0}
            footer={[
              {
                text: '取消',
                onPress: () => setDeleteOpen(false),
                style: { color: 'rgba(0, 0, 0, 0.5)',fontSize: 17 },
              },
              {
                text: '确认',
                onPress: () => handleDelete(),
                style: { color: '#2856FF',fontSize: 17 },
              },
            ]}
          >
            <Text style={{textAlign:'center',color: 'rgba(0,0,0,0.5)'}}>一旦删除，当前视频将被删除哦~</Text>
          </FcModal>
        </PageScrollView>
      </ImageBackground>
    </View>
  )
}

export default works

const styles = StyleSheet.create({
  works_box: {
    display: 'flex',
    flexDirection: 'column'
  },
  works_img_V: {
    width: 110,
    height: 195,
    marginRight: 8,
    borderRadius: 8,
    borderColor: '#ff9200',
    position: 'relative'
  },
  works_img_H: {
    width: '100%',
    height: 94,
    borderRadius: 8,
    borderColor: '#ff9200',
    position: 'relative',
    backgroundColor: '#232532',
    marginBottom: 8,
  },
  works_img_bottom: {
    position: 'absolute',
    bottom: 0,
    width: '100%',
  },
  works_active: {
    position: 'absolute',
    right: -1,
    bottom: -1,
    width: 0,
    height: 0,
    borderLeftWidth: 0,
    borderRightWidth: 30,
    borderBottomWidth: 30,
    borderLeftColor: 'rgba(0, 0, 0, 0.01)',
    borderBottomColor: 'rgba(0, 0, 0, 0.01)',
    borderRightColor: '#ff9200',
    transform: [{ rotate: '90deg' }],
    borderTopRightRadius: 8
  },
  works_active_icon: {
    fontFamily: 'FcIconFont',
    fontSize: 14,
    color: '#FFF',
    position: 'absolute',
    right: 1,
    bottom: 1
  }
})